import React, { PureComponent } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import querystring from 'querystring';
import G2 from '@antv/g2';
import { Table, Card, Button, Input, Form, Menu, Checkbox, Popconfirm, Modal, Select, Row, Col,
Popover, Dropdown, Icon, message, Radio, Tooltip, Cascader, DatePicker } from 'antd';
import { Link } from 'dva/router';
import TrimSpan from '../../components/TrimSpan';
import { RIGHT, CHANNELS, TASK_TYPES } from '../../constants';
import DockPanel from '../../components/DockPanel';
import TaskNameColumn from '../../components/TaskNameColumn';
import TaskStatusColumn from '../../components/TaskStatusColumn';
import styles from './index.less';

const Search = Input.Search;
const FormItem = Form.Item;
const { Option } = Select;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
const { RangePicker } = DatePicker;
const getValue = obj => Object.keys(obj).map(key => obj[key]).join(',');

@connect(state => ({
  data: state.statistics.statisticsChannel,
  loading: state.statistics.statisticsChannelLoading,
  teamUsers: state.team.teamUsers,
  teamUser: state.user.teamUser,
}))
@Form.create()
export default class StatisticsChannel extends PureComponent {
  state = {
    daren_id: undefined,
    channel_name: undefined,
    publish_taobao_time_start: null,
    publish_taobao_time_end: null,
  }

  componentWillMount() {
    const { dispatch, data, data: { pagination }, teamUser: { team_id, user_id } } = this.props;
    const { daren_id, channel_name } = this.state;
    const publish_taobao_time_start = new Date();
    publish_taobao_time_start.setDate(1);
    publish_taobao_time_start.setHours(0, 0, 0, 0);
    const publish_taobao_time_end = new Date();
    if (team_id) {
      this.props.dispatch({
        type: 'statistics/fetchStatisticsChannel',
        payload: { team_id, user_id, publish_taobao_time_start, publish_taobao_time_end,
          daren_id: this.props.daren_id || daren_id, channel_name },
      });
    }
    if (this.props.daren_id) {
      this.setState({ daren_id: this.props.daren_id });
    }
    this.setState({ publish_taobao_time_start, publish_taobao_time_end });
  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch, teamUser: { team_id, user_id } } = this.props;
    const { searchValue, publish_taobao_time_start, publish_taobao_time_end, daren_id, channel_name } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    const params = {
      team_id,
      user_id,
      daren_id,
      channel_name,
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
      search: searchValue,
      ...filters,
      publish_taobao_time_start,
      publish_taobao_time_end,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'statistics/fetchStatisticsChannel',
      payload: params,
    });
  }

  handleSearch = (value, name) => {
    const { dispatch, data: { pagination }, teamUser: { team_id, user_id } } = this.props;
    const { publish_taobao_time_start, publish_taobao_time_end, daren_id, channel_name } = this.state;
    const values = {
      team_id,
      user_id,
      publish_taobao_time_start,
      publish_taobao_time_end,
      daren_id,
      channel_name,
    };
    if(name === 'time') {
      values['publish_taobao_time_start'] = value[0] ? value[0].format('YYYY-MM-DD 00:00:00') : '';
      values['publish_taobao_time_end'] = value[1] ? value[1].format('YYYY-MM-DD 23:59:59') : '';
      this.setState({ publish_taobao_time_start: value[0].format('YYYY-MM-DD 00:00:00'), publish_taobao_time_end: value[1].format('YYYY-MM-DD 23:59:59') });
    } else {
      values[name] = value;
      this.setState({ [name]: values[name] });
    }
    dispatch({
      type: 'statistics/fetchStatisticsChannel',
      payload: { ...values, ...pagination},
    });
  }
  handleDarenChange = (daren_id) => {
    const { dispatch, data, data: { pagination }, teamUser: { team_id, user_id } } = this.props;
    const { taker_id, channel_name, publish_taobao_time_start, publish_taobao_time_end } = this.state;
    this.props.dispatch({
      type: 'statistics/fetchStatisticsChannel',
      payload: { team_id, user_id, publish_taobao_time_start, publish_taobao_time_end, daren_id, taker_id, channel_name },
    });
    this.setState({ daren_id });
  }
  disableDate = (current) => {
    let date = moment(current).format('L').replace(/\//g,'')
    return Number(date) < 20180310;
  }
  render() {
    const { data, loading, formData, form: { getFieldDecorator }, teamUsers } = this.props;
    const darenTeamUsers = teamUsers.filter(item => item.user_id && item.user_id.rights.indexOf(RIGHT.daren) >= 0);
    const columns = [
      {
        title: '渠道名称',
        dataIndex: 'activityId',
        fixed: 'left',
        render: (val, record) => {
          let title = '';
          if (record.activityId) {
            CHANNELS.forEach(item => {
              item.activityList.forEach(item1 => {
                if (item1.id === val) {
                  title = `${item.name} / ${item1.name}`;
                }
              });
            });
          } else {
            const taskType = TASK_TYPES.find(item => item.template === record.template);
            title = taskType ? `微淘 / ${taskType.text}` : ''
          }
          return (
            <TrimSpan text={title} length={30}/>
          )
        }
      },
      {
        title: '文章数',
        dataIndex: 'sumTaskCnt',
        sorter: true,
      },
      {
        title: '总阅读数',
        dataIndex: 'sumReadCnt',
        sorter: true,
      },
      {
        title: '平均阅读数',
        dataIndex: 'avgSumReadCnt',
        sorter: true,
        render: (val) => val.toFixed(2),
      },
      {
        title: '总进店数',
        dataIndex: 'sumCntIpv',
        sorter: true,
      },
      {
        title: '平均进店数',
        dataIndex: 'avgSumCntIpv',
        sorter: true,
        render: (val) => val.toFixed(2),
      },
    ];
    return (
      <div>
        <div className={styles.tableListOperator}>
          <Select
            allowClear
            showSearch
            style={{ width: 160, marginRight: 8 }}
            placeholder="渠道"
            onChange={(value) => this.handleSearch(value, 'channel_name')}
            optionFilterProp="children"
            filterOption={(input, option) => option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
            value={this.state.channel_name}
          >
            {CHANNELS.map(item => <Option key={item.id} value={item.name}>{item.name}</Option>)}
          </Select>
          <RangePicker allowClear={false} style={{ width: 240 }}
            value={[moment(this.state.publish_taobao_time_start || new Date()), moment(this.state.publish_taobao_time_end || new Date())]}
            onChange={(value) => this.handleSearch(value, 'time')}
            disabledDate={this.disabledDate}
          />
          <Tooltip placement="top" title="发布到阿里创作平台的时间">
            <Icon type="question-circle-o" style={{ margin: '0 2px 0 6px' }} />
          </Tooltip>
          {!this.props.daren_id && <Select
            allowClear={true}
            style={{ width: 240, marginLeft: 10 }}
            placeholder="发布者"
            value={this.state.daren_id}
            onChange={this.handleDarenChange}
            showSearch
            optionFilterProp="children"
          >
            {darenTeamUsers.map(teamUser => teamUser.user_id ? <Option key={teamUser.user_id._id} value={teamUser.user_id._id}>{teamUser.user_id.nickname}</Option> : '')
            }
          </Select>}
          {!this.props.daren_id &&
            <Tooltip style={{ float: 'right' }} placement="top" title="不选此项默认统计团队所有发布者的数据">
              <Icon type="question-circle-o" style={{ marginLeft: 10 }} />
            </Tooltip>}
        </div>
        <div style={{ marginTop: 20 }} className={styles.tableList}>
          <Table
            // scroll={{ x: 1200 }}
            loading={loading}
            dataSource={data.list}
            columns={columns}
            pagination={{
              showSizeChanger: true,
              showQuickJumper: true,
              ...data.pagination,
            }}
            onChange={this.handleStandardTableChange}
            rowKey={record => `${record.activityId}_${record.template}`}
          />
          <DockPanel />
        </div>
      </div>
    );
  }
}
